<template>
  <div class="eq_container eq_dashboard_container">
    <div class="app-container detail-head">
      <div class="top-block-frm">
        <div class="tt">
          {{ id ? '编辑模板' : '新增模板' }}
          <div>
            <el-button size="mini" type="success" icon="el-icon-check" @click="toSave" v-if="form.status!=2">保存</el-button>
            <el-button v-if="id && form.status !=2" size="mini" type="danger" icon="el-icon-delete" @click="toDelete">删除</el-button>
          </div>
        </div>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="small" v-loading="loading">
        <!-- 基本信息 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :md="12">
              <el-form-item label="模板名" prop="name">
                <el-input v-model="form.name" placeholder="请输入模板名称" clearable />
              </el-form-item>
            </el-col>

            <el-col :md="12">
              <el-form-item v-if="id" label="状态">
                <el-tag :type="statusTagType" effect="light">
                  {{ statusText }}
                </el-tag>
                <el-button
                  v-if="form.status === 0"
                  size="small"
                  class="ttrtbtn"
                  type="success"
                  style="margin-left: 10px;"
                  icon="el-icon-upload2"
                 @click="publish"
                >上架发布
                </el-button>
                <el-button
                  v-if="form.status === 1"
                  size="small"
                  class="ttrtbtn"
                  type="default"
                  style="margin-left: 10px;"
                 icon="el-icon-download"
                 @click="unPublish"
                >下架隐藏
                </el-button>
              </el-form-item>
             <!-- 新增时自己选状态 -->
              <el-form-item v-else label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
                  <el-option
                    v-for="item in productStatusOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 富文本编辑 -->
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">头部内容</div>
          <!-- <el-form-item label="头部页面URL" prop="head_url">
            <el-input v-model="form.head_url" placeholder="请输入模板头部内容页面URL" clearable />
          </el-form-item> -->
          <rc-editor
            api-key=""
            v-model="form.head_content"
          />
        </el-card>

        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">尾部内容</div>
          <!-- <el-form-item label="尾部页面URL" prop="footer_url">
            <el-input v-model="form.footer_url" placeholder="请输入模板尾部内容页面URL" clearable />
          </el-form-item> -->
          <rc-editor
            api-key=""
            v-model="form.footer_content"
          />
        </el-card>

        <!-- <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">JS内容</div>
          <el-form-item label="JS页面URL" prop="script_url">
            <el-input v-model="form.script_url" placeholder="请输入模板尾部内容页面URL" clearable />
          </el-form-item>
          <rc-editor
            api-key=""
            v-model="form.script_block"
          />
        </el-card>
        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">CSS内容</div>
          <el-form-item label="CSS页面URL" prop="style__url">
            <el-input v-model="form.style__url" placeholder="请输入模板尾部内容页面URL" clearable />
          </el-form-item>
          <rc-editor
            api-key=""
            v-model="form.style_block"
          />
        </el-card> -->

        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">JS 内容</div>
          <code-editor
            v-model="form.script_block"
            language="js"
          />
        </el-card>

        <el-card shadow="never" class="mb-2">
          <div slot="header" class="left-title">CSS 内容</div>
            <code-editor
              v-model="form.style_block"
              language="css"
            />
        </el-card>
      </el-form>
    </div>
  </div>
</template>

<script>
import { aliClientInit, ossFilePath } from '@/api/common'
import { getTemplateById, editTemplateById } from '@/api/product'
import RcEditor from '@/layout/components/Editor/index.vue'
import CodeEditor from '@/layout/components/CodeEditor/index.vue'

export default {
  name: 'ProductEdit',
  components: { 
    // Editor,
    RcEditor,
    CodeEditor
   },
  data() {
    return {
      id: '',
      loading: false,
      statusText: '',     
      statusTagType: '', 
      productStatusOption: this.hashmap.productStatusOption,

      form: {
        name: '',
        status: 1,
        head_content:'',
        head_url:'',
        footer_content:'',
        footer_url:'',
        script_block:'',
        style_block:'',
        script_url:'',
        style__url:''
      },

      
      rules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
      },
    }
  },

  watch: {
    '$route.query.id'(newId) {
      this.id = newId || null
      if (this.id) {
        this.getProductByID()
      }
    }
  },

  computed: {
  },


  created() {
    this.id = this.$route.query.id || null
    if (this.id) this.getTemplateById()

    this.aliOssInit()
  },

  methods: {
    async aliOssInit() {
      this.AliClient = await aliClientInit()
    },
    getTemplateById () {
      this.loading = true
      getTemplateById ({
       template_id: this.id
      }).then((res) => {
        if (res && res.code === 0 && res.data) {
          const data = res.data
          this.form = res.data
          this.statusText=this.findJsonByKeyValue(this.productStatusOption, 'value', data.status).label || ''
          this.statusTagType=this.findJsonByKeyValue(this.productStatusOption, 'value', data.status).typeClass || ''
        }
      }).finally(()=>{
        this.loading = false
      })
    },

    toSave() {
      const $this = this
      $this.$refs.formRef.validate(valid => {
        if (!valid) return
        $this.$confirm('确认提交？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          $this.loading = true
          const isEdit = !!$this.id
          const params = { ...$this.form }

          // 编辑时带上 template_id
          if (isEdit) {
            params.template_id = Number($this.id)
          }
          console.log('保存模板传参：', params)

          editTemplateById(params)
            .then((res) => {
              if (res && res.code === 0) {
                const newId = isEdit ? $this.id : (res.data && res.data.id)
                $this.$message.success(isEdit ? '修改成功' : '新增成功')
                
                // this.$router.push({
                //   path: `/template/templateList`
                // })
                
                if (!isEdit && newId) {
                  $this.$router.replace({
                    path: '/template/templateDetail',
                    query: { id: newId }
                  })
                  $this.id = newId
                  $this.getTemplateById()
                }

                if (isEdit) {
                  $this.getTemplateById()
                }
              } else {
                $this.$message.error(res?.msg || (isEdit ? '修改失败' : '新增失败'))
              }
            })
            .finally(() => {
              $this.loading = false
            })
        }).catch(() => {})
      })
    },

    // 通用状态更新方法
    updateStatus (newStatus, confirmText, successMsg, afterSuccess) {
      if (!this.id) return

      this.$confirm(confirmText, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        editTemplateById({
          template_id: Number(this.id),
          status: newStatus
        })
          .then(res => {
            if (res && res.code === 0) {
              if (newStatus == 1 ) {
                this.form.status = newStatus
              }
              this.$message.success(successMsg)

              if (typeof afterSuccess === 'function') {
                afterSuccess()
              }
            } else {
              this.$message.error(res?.msg || '操作失败')
            }
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {})
    },

    // 删除：status = 2
    toDelete () {
      this.updateStatus(2,'确认是否删除该模板？','删除成功',() => {
        this.$router.push({ path: '/template/templateList' })
      })
    },

     // 上架：status = 1
    publish () {
      this.updateStatus(1,'确认将该模板上架发布吗？','上架成功')
    },

    // 下架：status = 0
    unPublish () {
      this.updateStatus(0,'确认将该模板下架隐藏吗？','下架成功',() => {
        this.$router.push({ path: '/template/templateList' })
      })
    },


  }
}
</script>

<style scoped>
.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 8px;
  border-radius: 8px;
  border: 1px solid #eee;
}
.mb-2 { margin-bottom: 16px; }
.mt-2 { margin-top: 12px; }

.left-title{
  padding-left: 5px;
  border-left: 3px solid #4974e1;
}
</style>
